<?php
namespace app\index\common;

class Tree {
    public $arr = [];
    public function init($arr = []) {
        $this->arr = $arr;
        return is_array($arr);
    }

    public function getChild($id) {
        $res = [];
        if (is_array($this->arr)) {
            foreach ($this->arr as $k => $v) {
                if ($v["pid"] == $id) {
                    $res[$k] = $v;
                }
            }
        }
        return $res ? $res : false;
    }
    public function getNav($id = 0, $str = "", $currentlevel = 0, $limitLevel = 2) {

        $child = $this->getChild($id);
        if (is_array($child)) {
            foreach ($child as $k => $v) {
                $subChild = $this->getChild($v["id"]);
                if ($subChild) {
                    $currentlevel++;
                    if ($currentlevel < $limitLevel) {
                        $str .= '<li class="dropdown"><a href="' . url("index/category/article", "id=" . $v["id"]) . '" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="100" role="button" aria-expanded="false">' . $v["name"] . '<span class="caret"></span></a><ul class="dropdown-menu" role="menu">';
                        $str = $this->getNav($v["id"], $str, $currentlevel);
                        $str .= "</ul></li>";
                        $currentlevel = 0;
                    } else {
                        $str .= '<li><a href="' . url("index/category/article", "id=" . $v["id"]) . '">' . $v["name"] . '</a></li>';
                    }

                } else {
                    $str .= '<li><a href="' . url("index/category/article", "id=" . $v["id"]) . '">' . $v["name"] . '</a></li>';
                }

            }
        }

        return $str;
    }
}

?>